package com.uniledger.exchange.dapp;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.just.agentweb.AgentWeb;
import com.uniledger.commonlib.pinkeyboard.IKeyboardListener;
import com.uniledger.commonlib.pinkeyboard.IThirdPayListener;
import com.uniledger.commonlib.pinkeyboard.KeyboardDialog;
import com.uniledger.commonlib.pinkeyboard.PayThirdResult;
import com.uniledger.commonlib.pinkeyboard.ThirdPayInfo;
import com.uniledger.exchange.R;
import com.uniledger.exchange.home.HomeCenter;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.stellar.TransactionUtils;

import org.reactivestreams.Publisher;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.uniledger.commonlib.bigdecimalutils.BigDecimalUtils.is;


public class AndroidInterface implements IThirdPayListener, IKeyboardListener {

    private Handler deliver = new Handler(Looper.getMainLooper());
    private AgentWeb agent;
    private Activity context;

    private OnJsListener onJsListener;
    private KeyboardDialog pinDialog;

    public void closePinDialog() {
        if (pinDialog != null) {
            pinDialog.clearPassword();
            pinDialog.dismiss();
        }
    }

    private void showPayKeyBoard(String data) {
        if (pinDialog == null) {
            pinDialog = new KeyboardDialog(context, true);
            pinDialog.setKeyboardListener(this);
            pinDialog.setPayListener(this::onThirdComplete);

        }
        pinDialog.show();
        pinDialog.showError(View.GONE);
        pinDialog.setThirdPayInfo(new ThirdPayInfo(data, OkSingleton.getInstance().getCurrencyCode()));
    }


    public AndroidInterface(Activity context, AgentWeb agent) {
        this.context = context;
        this.agent = agent;
    }

    public void setOnJsListener(OnJsListener onJsListener) {
        this.onJsListener = onJsListener;
    }

    @JavascriptInterface
    public String pay(String data) {
        deliver.post(new Runnable() {
            @Override
            public void run() {
                //TODO
                showPayKeyBoard(data);
            }
        });
        return "OK";
    }

    private void signAndPay(String data, ThirdPayInfo thirdPayInfo) {
        //TODO 支付
        String uniswitch = "GBMRA7PEMA244EWSHYQSICTPXVXYETXKR6LDNA7ZWCOE4UE54FA4LJTD";
        //解析信息 展示
        String amount = thirdPayInfo.payInfo.balance;
        Map<String, String> params = new HashMap<>();
        params.put("payee_id", "37");
        params.put("currency", OkSingleton.getInstance().getCurrencyCode());
        params.put("remark", "Pay");
        params.put("amount", amount);
        params.put("AccountId", uniswitch);
        params.put("name", context.getResources().getString(R.string.dapp_uni_name));

        //处理签名
        TransactionUtils.transaction(amount, data, uniswitch)
                .flatMap(new Function<String, Publisher<HttpResult<PayThirdResult>>>() {
                    @Override
                    public Publisher<HttpResult<PayThirdResult>> apply(String sign) throws Exception {
                        params.put("stellar_trx_sign", sign);
                        return Api.getService().doThirdTransfer(params);
                    }
                }).compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(context))
                .subscribe(new Consumer<HttpResult<PayThirdResult>>() {
                    @Override
                    public void accept(HttpResult<PayThirdResult> httpResult) throws Exception {
                        PayThirdResult result = httpResult.data;
                        if (!TextUtils.isEmpty(httpResult.msg)) {
                            result.errorMessage = httpResult.msg;
                        }
                        result.setFlag(HomeCenter.SCHEME_TRANSFER);
                        result.currencyCode = OkSingleton.getInstance().getCurrencyCode();
                        result.currencySymbol = OkSingleton.getInstance().getSymbol();
                        result.amount = thirdPayInfo.payInfo.balance;
//                        pinDialog.showOkData(result);

                        if (httpResult.code == 0) {
                            onJsListener.onJsSuccess(httpResult.data.hashStr);
                        } else {
                            onJsListener.onJsFailed(httpResult.data.hashStr);
                        }
                        closePinDialog();
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onJsListener.onJsFailed(throwable.getMessage());
                        closePinDialog();
                    }
                }));
    }

    @Override
    public void onThirdComplete(String pwd, ThirdPayInfo payInfo) {

        //TODO 判断金额是否足够
        String balance = OkSingleton.getInstance().getAssetBalance();
        if (is(balance).gteq(payInfo.payInfo.balance)) {
            pinDialog.showError(View.GONE);
            signAndPay(payInfo.data, payInfo);
        } else {
            pinDialog.showError(View.VISIBLE);
        }
    }

    @Override
    public void onPasswordChange(String pwd) {

    }

    @Override
    public void onPasswordComplete(String pwd) {

    }

    @Override
    public void onForgetPwd() {

    }

    public interface OnJsListener {
        void onJsSuccess(String result);

        void onJsFailed(String error);
    }

}
